package com.jf.mall.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-09-27
 * Time:1:00
 */
public class DataUtils {
    /**
     * 将请求参数封装成指定类对象
     * @param params 参数Map<属性, 值>
     * @param clazz 待封装的类
     * @return 封装后的对象, 封装报错返回null
     * @param <T> 泛型类声明
     */
    public static <T> T copyParamToBean(Map<String, String[]> params, Class<T> clazz) {
        T t = null;
        try {
            t = clazz.getDeclaredConstructor().newInstance();
            BeanUtils.populate(t, params);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException |
                 ConversionException e) {
            e.printStackTrace();
        }
        return t;
    }

    public static int parseInt(String str, int defaultValue) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            System.out.println("The String [" + str + "] is not a number");
        }
        return defaultValue;
    }
    public static int parseInt(String str) {
        return parseInt(str, 0);
    }
}
